using System;
using System.Collections.Generic;
using System.IO;

namespace Pronghorn.Core
{
	public class SimpleFileMinifier : IFileMinifier
	{
		private bool _blockCommentOn;

		private string removeBlockComment(string line)
		{
			line = removeBlockCommentStart(line);
			line = removeBlockCommentEnd(line);
			if (_blockCommentOn)
			{
				line = string.Empty;
			}
			return line;
		}

		private string removeBlockCommentEnd(string line)
		{
			if (line.IndexOf("*/") > -1)
			{
				_blockCommentOn = false;
				return line.Remove(0,(line.IndexOf("*/")+2));	
			}
			return line;
		}

		private string removeBlockCommentStart(string line)
		{
			if (line.IndexOf("/*") > -1)
			{
				_blockCommentOn = true;
				return line.Remove(line.IndexOf("/*"));
			}
			return line;
		}

		private static string removeInlineComment(string line)
		{
			//This will only remove one liners when they are at the beginning of the line, if not we may risk to break urls
			if (line.Trim().IndexOf("//")== 0)
			{
				return line.Remove(line.IndexOf("//"));
			}
			if(line.IndexOf("/*")> -1 && line.IndexOf("*/")> -1)
			{
				var startPosition = line.IndexOf("/*");
				var endPosition = line.IndexOf("*/") + 2;
				return line.Remove(startPosition, (endPosition - startPosition));
			}
			return line;
		}

		public void Minify(List<string> sourceCode, StringWriter writer)
		{
			//string splitter = findLineSplit(sourceCode);
			//var scriptLines = sourceCode.Split(new[] { splitter }, StringSplitOptions.RemoveEmptyEntries);

			foreach (var scriptLine in sourceCode)
			{
				var filteredLine = removeInlineComment(scriptLine);
				filteredLine = removeBlockComment(filteredLine);
				filteredLine = filteredLine.Trim();

				if (filteredLine.Length > 0)
				{
					writer.WriteLine(filteredLine);
				}
			}
		}

		private string findLineSplit(string sourceCode)
		{
			string splitter = "\r\n";
			if (!sourceCode.Contains(splitter))
			{
				splitter = "\n\n";
			}
			return splitter;
		}
	}
}